<script setup lang="ts">
import { ref, watch, nextTick, type ComponentPublicInstance } from "vue"
import * as echarts from "echarts"
import "echarts/renderers"
import { getStatisticsIssueApi } from "@/api/billv2"
import columnars from "./columnar.vue"

interface DataItem {
  name: string
  value: number
  manual: number
}

const chartRef = ref<any>(null)
const columnarsRef = ref<ComponentPublicInstance<InstanceType<typeof columnars>> | null>(null)
// const chartRef2 = ref<any>(null)
const listData = ref<any[]>([])
const listData2 = ref<any[]>([])
const sum = ref<string>("0")
const total = ref<number>(0)

const props = defineProps({
  enterTimeStart: {
    type: String,
    required: true
  },
  enterTimeEnd: {
    type: String,
    required: true
  }
})
const getTable = () => {
  getStatisticsIssueApi({ startTime: props.enterTimeStart, endTime: props.enterTimeEnd }).then((res: any) => {
    // listData.value = res.data.type
    listData.value = res.data.type.map((item: any) => ({
      name: item.name,
      value: item.value,
      manual: item.manual
      // 确保包含 manual 属性
    }))
    listData2.value = res.data.count
    sum.value = res.data.typeNum
    total.value = res.data.countNum
    nextTick(() => {
      echartsInit()
    })
  })
}
const echartsInit = () => {
  if (chartRef.value) {
    console.log(listData)
    const chartInstance = echarts.init(chartRef.value)
    const option = {
      title: { text: "" },
      tooltip: { trigger: "item" },
      legend: {
        orient: "vertical",
        left: "left"
      },
      series: [
        {
          name: "",
          type: "pie",
          radius: "50%",
          data: listData.value,
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: "rgba(0, 0, 0, 0.5)"
            }
          }
        }
      ]
    }
    chartInstance.setOption(option)
    // 处理点击事件并且跳转到相应的百度搜索页面
    chartInstance.on("click", function (params) {
      console.log("click")
      console.log(params)
      const dataItem = params.data as DataItem
      if (columnarsRef.value && dataItem.manual == 1) {
        columnarsRef.value.batchShow({
          type: dataItem.manual,
          startTime: props.enterTimeStart,
          endTime: props.enterTimeEnd,
          libraryType: 2
        })
      }
      // window.open("https://www.baidu.com/s?wd=" + encodeURIComponent(params.name))
    })
  }
}
watch([() => listData, () => props.enterTimeStart, () => props.enterTimeEnd], getTable, { immediate: true })
</script>

<template>
  <div>
    <div>总金额：{{ sum }}</div>
    <div ref="chartRef" style="height: 400px" />
    <!-- <div></div>
    <div ref="chartRef2" style="height: 400px" /> -->
    <columnars ref="columnarsRef" />
  </div>
</template>

<style scoped lang="scss"></style>
